import crypto from 'crypto';
import jwt from 'jsonwebtoken';
import { logger } from './logger';
import config from '../config/env';

/**
 * 生成密码重置令牌
 */
export const generateResetToken = (userId: string, email: string): string => {
  const payload = {
    userId,
    email,
    type: 'password_reset',
    timestamp: Date.now()
  };

  // 生成6小时有效期的重置令牌
  return jwt.sign(payload, config.JWT_SECRET, { expiresIn: '6h' });
};

/**
 * 验证密码重置令牌
 */
export const verifyResetToken = (token: string): {
  userId: string;
  email: string;
  type: string;
} | null => {
  try {
    const decoded = jwt.verify(token, config.JWT_SECRET) as any;
    
    if (decoded.type !== 'password_reset') {
      logger.warn('重置令牌验证失败: 类型错误', { type: decoded.type });
      return null;
    }

    return {
      userId: decoded.userId,
      email: decoded.email,
      type: decoded.type
    };
  } catch (error: any) {
    logger.warn('重置令牌验证失败', { error: error.message });
    return null;
  }
};

/**
 * 生成安全的随机码（用于邮件验证等）
 */
export const generateSecureCode = (length: number = 6): string => {
  const digits = '0123456789';
  let result = '';
  
  for (let i = 0; i < length; i++) {
    result += digits[crypto.randomInt(0, digits.length)];
  }
  
  return result;
};

/**
 * 生成密码重置链接
 */
export const generateResetLink = (token: string, baseUrl?: string): string => {
  const resetBaseUrl = baseUrl || process.env.FRONTEND_URL || 'http://localhost:3000';
  return `${resetBaseUrl}/reset-password?token=${token}`;
};

/**
 * 检查重置令牌是否即将过期（1小时内）
 */
export const isTokenNearExpiry = (token: string): boolean => {
  try {
    const decoded = jwt.decode(token) as any;
    if (!decoded || !decoded.exp) return true;
    
    const expiryTime = decoded.exp * 1000;
    const currentTime = Date.now();
    const oneHour = 60 * 60 * 1000;
    
    return (expiryTime - currentTime) < oneHour;
  } catch {
    return true;
  }
};